package com.tuocent.dagv2.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tuocent.dagv2.common.AjaxResult;
import com.tuocent.dagv2.common.entity.LoginUserInfo;
import com.tuocent.dagv2.common.utils.PublicUtil;
import com.tuocent.dagv2.common.utils.SnowFlakeID;
import com.tuocent.dagv2.common.utils.redis.RedisCache;
import com.tuocent.dagv2.constant.PublicConst;
import com.tuocent.dagv2.entity.*;
import com.tuocent.dagv2.mapper.ArchivesImportMapper;
import com.tuocent.dagv2.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Future;

import static com.tuocent.dagv2.common.utils.TCUtil.camelToSnake;

/**
 * <p>
 * 数据导入信息 服务实现类
 * </p>
 *
 * @author Vincent
 * @since 2025-09-12
 */
@Service
@Slf4j
public class ArchivesImportServiceImpl extends ServiceImpl<ArchivesImportMapper, ArchivesImport> implements IArchivesImportService {
    @Value("${location.upload-dir}")
    private String uploadPath;
    @Value("${location.mount-dir}")
    private String mountPath;

    @Resource
    private SnowFlakeID snowFlakeID;
    @Resource
    private RedisCache redis;
    @Autowired
    private IProjectsService projectsService;
    @Autowired
    private ITaskService taskService;
    @Autowired
    private IFieldConfigService fieldConfigService;
    @Autowired
    private IArchivesReceiveService archivesReceiveService;
    @Autowired
    private IArchivesRecordService recordService;
    @Autowired
    private IArchivesFilesService filesService;
    @Autowired
    private IArchivesLogsService archivesLogsService;
    @Autowired
    private IArchivesInfoService archivesInfoService;
    @Autowired
    private IArchivesImportLogService archivesImportLogService;
    @Autowired
    private IArchivesDigitalFileService digitalFileService;

    @Override
    public String archivesImport(Model model) {
        List<Projects> projectsList = projectsService.list(new QueryWrapper<Projects>().eq("is_del", "0"));
        model.addAttribute("projectsList", projectsList);
        return "/import/archivesImport";
    }

    @Override
    public AjaxResult getArchivesImportData(Map<String, Object> params) {
        int limit = PublicConst.DEF_LIMIT;
        int page = PublicConst.DEF_PAGE;
        QueryWrapper<ArchivesImport> qw = new QueryWrapper<ArchivesImport>()
                .eq("import_model", "1")
                .orderByAsc("status")
                .orderByDesc("upload_time");
        for (String key : params.keySet()) {
            String keyValue = params.get(key).toString();
            if (keyValue.trim().isEmpty()) {
                continue;
            }
            switch (key) {
                case "limit":
                    limit = Integer.parseInt(keyValue);
                    break;
                case "page":
                    page = Integer.parseInt(keyValue);
                    break;
                default:
                    qw.eq(key, keyValue);
                    break;
            }
        }
        Page<ArchivesImport> data = page(new Page<>(page, limit), qw);
        return AjaxResult.success(data.getRecords(), data.getTotal());
    }

    @Override
    public void getDataTemplate(HttpServletResponse response, String pid, String tid, String model) throws IOException {
        String fileName = switch (model) {
            case "1" -> "文件目录";
            case "2" -> "案卷目录";
            case "3" -> "项目目录";
            default -> "";
        };
        Task task = taskService.getOne(new QueryWrapper<Task>()
                .eq("pid", pid)
                .eq("id", tid)
                .last("limit 1"));
        if (task != null) {
            List<FieldConfig> data = fieldConfigService.list(new QueryWrapper<FieldConfig>()
                    .eq("classify_id", task.getArchivesClassifyId())
                    .eq("filling_model", model)
                    .orderByAsc("show_idx"));
            if (data != null) {
                Workbook workbook = new HSSFWorkbook();
                Sheet sheet = workbook.createSheet(fileName);
                Row header = sheet.createRow(0);
                CellStyle style = workbook.createCellStyle();
                style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
                style.setFillForegroundColor(IndexedColors.GOLD.getIndex());
                int col = 0;
                for (FieldConfig field : data) {
                    Cell cell = header.createCell(col);
                    if ("1".equals(field.getIsMust()) || "1".equals(field.getIsOnly())) {
                        cell.setCellStyle(style);
                    }
                    cell.setCellValue(field.getFieldTitle());
                    col++;
                }
                response.setContentType("application/vnd.ms-excel;charset=utf-8");
                response.setHeader("Content-Disposition", "attachment;filename=" +
                        URLEncoder.encode(task.getTaskName() + fileName + "导入模板.xlsx", StandardCharsets.UTF_8));
                workbook.write(response.getOutputStream());
                workbook.close();
            }
        }
    }

    @Override
    public String setArchivesImportData(Model model, String pid, String tid, String id, String importModel) {
        ArchivesImport data = getById(id);
        if (data == null) {
            data = new ArchivesImport();
            data.setPid(pid);
            data.setTid(tid);
        }
        model.addAttribute("data", data);
        model.addAttribute("pid", pid);
        model.addAttribute("importModel", importModel);
        String uri = "/workflow/setArchivesImportFile";
        switch (importModel) {
            case "1":
                List<ArchivesReceive> archivesReceiveList = archivesReceiveService.list(new QueryWrapper<ArchivesReceive>()
                        .select("batch_code")
                        .eq("pid", pid)
                        .eq("tid", tid)
                        .eq("is_del", "0"));
                model.addAttribute("archivesReceiveList", archivesReceiveList);
                break;
            case "2":
                uri = "/workflow/setNotBatchArchivesImportFile";
                break;
        }
        return uri;
    }

    @Override
    public AjaxResult ImportArchivesFile(HttpSession session, String pid, String tid, Integer model, String batchCode, MultipartFile file) {
        if (file.isEmpty()) {
            return AjaxResult.error("上传失败，请选择文件");
        }
        if (model == 0) {
            return AjaxResult.error("无效的类别目录数据");
        }
        Task task = taskService.getOne(new QueryWrapper<Task>().eq("pid", pid)
                .eq("id", tid).eq("is_del", "0"));
        if (task == null) {
            return AjaxResult.error("没有找到改任务的数据");
        }
        LoginUserInfo loginUser = redis.get(session.getId());
        File dir = new File(uploadPath + "/archivesImport/" + batchCode + "/");
        if (!dir.exists()) {
            try {
                if (!dir.mkdirs()) {
                    log.error("创建文件上传目录失败。");
                    return AjaxResult.error("创建文件上传目录失败。");
                }
            } catch (Exception e) {
                log.error(e.getMessage());
                return AjaxResult.error("创建文件上传目录失败。错误信息：" + e);
            }
        }
        String fileName = file.getOriginalFilename();
        String part = dir.getPath() + File.separator;
        File dest = new File(part + fileName);
        try {
            file.transferTo(dest);

            ArchivesImport input = new ArchivesImport();
            input.setId(snowFlakeID.getId());
            input.setPid(pid);
            input.setTid(tid);
            input.setBatchCode(batchCode);
            input.setClassifyId(task.getArchivesClassifyId());
            input.setModel(model);
            input.setStatus(0);
            input.setFilename(fileName);
            input.setPatch(part);
            input.setImportModel("1");
            input.setUploadTime(LocalDateTime.now());
            input.setUploader(loginUser.getUserName());
            return save(input) ? AjaxResult.success("文件上传成功") : AjaxResult.error("文件上传保存失败");
        } catch (IOException e) {
            log.error(e.getMessage());
            return AjaxResult.error("文件上传失败。错误信息：" + e);
        }
    }

    @Override
    public AjaxResult delArchivesImport(String id) {
        return removeById(id) ? AjaxResult.success("删除数据成功") : AjaxResult.error("删除数据失败");
    }

    @Override
    @Async
    public Future<Integer> archivesImportExecute(LoginUserInfo loginUser, String id) throws IOException {
        ArchivesImport data = getById(id);
        if (data == null) {
            log.error("数据为空");
            return null;
        }
        data.setStatus(1);
        data.setExecutionTime(LocalDateTime.now());
        data.setExecutor(loginUser.getUserName());
        updateById(data);
        //检测文件是否存在
        String fileName = data.getPatch() + data.getFilename();
        File file = new File(fileName);
        if (!file.exists()) {
            data.setStatus(3);
            data.setInfo("数据文件不存在");
            updateById(data);
            log.info("数据文件不存在");
            return CompletableFuture.completedFuture(0);
        }

        Workbook workbook = null;
        try {
            InputStream excelFile = new FileInputStream(fileName);
            System.err.println(fileName);
            try {
                workbook = WorkbookFactory.create(new File(fileName));
                if (workbook == null) {
                    data.setStatus(3);
                    data.setInfo("数据文件格式不正确");
                    updateById(data);
                    log.error("数据文件格式不正确");
                    return CompletableFuture.completedFuture(0);
                }
            } catch (Exception e) {
                data.setStatus(3);
                data.setInfo(e.getMessage());
                updateById(data);
                log.error(e.getMessage());
                return CompletableFuture.completedFuture(0);
            }
            //读取第一个sheet 系统只支持读取第一个
            Sheet sheet = workbook.getSheetAt(0);
            //最大行数
            int row = sheet.getLastRowNum();
            log.info("数据行数：{}", row);
            if (sheet.getRow(PublicConst.InMaxRow) != null || row > PublicConst.InMaxRow) {
                data.setStatus(3);
                data.setInfo("数据单次导入不可超过" + PublicConst.InMaxRow + "条数据");
                log.info("数据单次导入不可超过" + PublicConst.InMaxRow + "条数据");
                updateById(data);
                workbook.close();
                return CompletableFuture.completedFuture(0);
            }

            //第一行
            Row firstRow = sheet.getRow(sheet.getFirstRowNum());
            //取文件字段信息
            Map<String, Integer> cols = new HashMap<>();
            for (int j = firstRow.getFirstCellNum(); j <= firstRow.getLastCellNum(); j++) {
                Cell cell = firstRow.getCell(j);
                String cellValue = PublicUtil.getCellValue(cell);
                if (!cellValue.trim().isEmpty()) {
                    cols.put(cellValue, j);
                }
            }

            //获取门类字段信息
            List<FieldConfig> fieldConfigList = fieldConfigService.list(new QueryWrapper<FieldConfig>()
                    .eq("classify_id", data.getClassifyId())
                    .eq("filling_model", data.getModel()));
            if (fieldConfigList == null || fieldConfigList.isEmpty()) {
                workbook.close();
                data.setStatus(3);
                data.setInfo("没有找到档案门类配置信息");
                log.info("没有找到档案门类配置信息");
                updateById(data);
                return CompletableFuture.completedFuture(0);
            }
            //循环所有字段信息，获取需要的内容
            Map<String, String> fieldsList = new HashMap<>();     //字段列表
            Map<String, String> mustList = new HashMap<>();
            Map<String, String> mustFields = new HashMap<>();     //必填字段列表
            Map<String, String> onlyFields = new HashMap<>();     //唯一字段列表
            Map<String, String> makeOnlyFields = new HashMap<>(); //组合唯一字段列表
            Map<String, String> parentFields = new HashMap<>();   //上级关联字段列表
            for (FieldConfig fieldConfig : fieldConfigList) {
                String filedName = fieldConfig.getFieldName();
                fieldsList.put(fieldConfig.getFieldTitle(), filedName);
                if ("1".equals(fieldConfig.getIsMust())) {
                    mustFields.put(fieldConfig.getFieldTitle(), filedName);
                    if (!mustList.containsKey(fieldConfig.getFieldTitle())) {
                        mustList.put(fieldConfig.getFieldTitle(), filedName);
                    }
                }
                if ("1".equals(fieldConfig.getIsOnly())) {
                    onlyFields.put(fieldConfig.getFieldTitle(), filedName);
                    if (!mustList.containsKey(fieldConfig.getFieldTitle())) {
                        mustList.put(fieldConfig.getFieldTitle(), filedName);
                    }
                }
                if ("1".equals(fieldConfig.getIsMakeonly())) {
                    makeOnlyFields.put(fieldConfig.getFieldTitle(), filedName);
                    if (!mustList.containsKey(fieldConfig.getFieldTitle())) {
                        mustList.put(fieldConfig.getFieldTitle(), filedName);
                    }
                }
                //上级字段列表
                if ("4".equals(fieldConfig.getDatasrcModel())) {
                    parentFields.put(fieldConfig.getFieldTitle(), fieldConfig.getDatasrcCorresponding());
                    if (!mustList.containsKey(fieldConfig.getFieldTitle())) {
                        mustList.put(fieldConfig.getFieldTitle(), filedName);
                    }
                }
            }

            //检测数据列
            StringBuilder notFields = new StringBuilder();
            for (String key : mustList.keySet()) {
                if (!cols.containsKey(key)) {
                    notFields.append(key).append(" ");
                }
            }
            //如果必填字段不存在，侧不导入
            if (!notFields.isEmpty()) {
                workbook.close();
                data.setStatus(3);
                data.setInfo("必填字段列表 " + notFields + " 不存在，不可导入");
                updateById(data);
                return CompletableFuture.completedFuture(0);
            }

            QueryWrapper<?> query = null;
            switch (data.getModel()) {
                case 1:
                    query = new QueryWrapper<ArchivesRecord>();
                    break;
                case 2:
                    query = new QueryWrapper<ArchivesFiles>();
                    break;
                case 3:
                    //query = new QueryWrapper<ArchivesProject>();
                    break;
            }

            int errNum = 0;
            int accNum = 0;
            int updateNum = 0;
            int InNum = 0;
            long startTime = System.currentTimeMillis();
            for (int i = 1; i <= row; i++) {
                Row nRow = sheet.getRow(i);
                //如果是空行，侧退出本次循环
                if (nRow == null) {
                    continue;
                }
                //开始检测数据
                //检测必填字段
                StringBuilder mustValue = new StringBuilder();
                for (String key : mustFields.keySet()) {
                    Cell cell = nRow.getCell(cols.get(key));
                    String cellValue = PublicUtil.getCellValue(cell);
                    if (cellValue.trim().isEmpty()) {
                        mustValue.append(key).append(" ");
                    }
                }
                //如果必填字段不存在，侧不导入
                if (!mustValue.isEmpty()) {
                    workbook.close();
                    LogData(data.getId(), i, "必填字段 " + mustValue + " 为空，不可导入");
                    errNum++;
                    continue;
                }

                //如果有上级字段，侧查询关联信息
                Map<String, String> onlyValue = new HashMap<>();
                String parentId = "";
                if (!parentFields.isEmpty()) {
                    switch (data.getModel()) {
                        case 1:
                            QueryWrapper<ArchivesFiles> fileQuery = new QueryWrapper<>();
                            fileQuery.eq("pid", data.getPid())
                                    .eq("tid", data.getTid())
                                    .eq("is_del", "0");
                            for (String key : parentFields.keySet()) {
                                Cell cell = nRow.getCell(cols.get(key));
                                String cellValue = PublicUtil.getCellValue(cell);
                                fileQuery.eq(camelToSnake(parentFields.get(key)), cellValue);
                                onlyValue.put(key, cellValue);
                            }
                            ArchivesFiles parentFile;
                            try {
                                parentFile = filesService.getOne(fileQuery);
                            } catch (Exception e) {
                                LogData(data.getId(), i, onlyValue + e.getMessage());
                                errNum++;
                                continue;
                            }
                            if (parentFile == null) {
                                workbook.close();
                                LogData(data.getId(), i, "没有找到 " + onlyValue + " 的案卷，不可导入");
                                errNum++;
                                continue;
                            } else {
                                parentId = parentFile.getId();
                            }
                            break;
                        case 2:
                            /*
                            QueryWrapper<ArchivesProject> projectQuery = new QueryWrapper<>();
                            projectQuery.eq("pid", data.getPid())
                                    .eq("tid", data.getTid())
                                    .eq("isdel", "0");
                            for (String key : parentFields.keySet()) {
                                Cell cell = nRow.getCell(cols.get(key));
                                String cellValue = PublicUtil.getCellValue(cell);
                                projectQuery.eq(parentFields.get(key), cellValue);
                                onlyValue.put(key, cellValue);
                            }
                            ArchivesProject parentProject;
                            try {
                                parentProject = projectService.getOne(projectQuery);
                            } catch (Exception e) {
                                LogData(data.getId(), i, onlyValue + " 的项目不是唯一，无法获取上级数据");
                                errNum++;
                                continue;
                            }
                            if (parentProject == null) {
                                workbook.close();
                                LogData(data.getId(), i, "没有找到 " + onlyValue + " 的案卷，不可导入");
                                errNum++;
                                continue;
                            } else {
                                parentId = parentProject.getId();
                            }

                             */
                            break;
                    }
                }

                //检测唯一数据是否存在
                Cell cell;
                onlyValue.clear();
                String onlyId = "";
                for (String field : onlyFields.keySet()
                ) {
                    cell = nRow.getCell(cols.get(field));
                    String cellValue = PublicUtil.getCellValue(cell).trim();
                    if (!cellValue.isEmpty()) {
                        assert query != null;
                        query.clear();
                        query.eq("pid", data.getPid())
                                .eq("tid", data.getTid())
                                .eq("is_del", "0")
                                .eq(camelToSnake(onlyFields.get(field)), cellValue);
                        if (!"".equals(parentId)) {
                            query.eq("parent_id", parentId);
                        }
                        query.last("limit 0, 1");

                        switch (data.getModel()) {
                            case 1:
                                ArchivesRecord orData = recordService.getOne((Wrapper<ArchivesRecord>) query);
                                if (orData != null) {
                                    onlyId = orData.getId();
                                }
                                break;
                            case 2:
                                ArchivesFiles ofData = filesService.getOne((Wrapper<ArchivesFiles>) query);
                                if (ofData != null) {
                                    onlyId = ofData.getId();
                                }
                                break;
                            case 3:
                                /*
                                ArchivesProject opData = projectService.getOne((Wrapper<ArchivesProject>) query);
                                if (opData != null) {
                                    onlyId = opData.getId();
                                }

                                 */
                                break;
                        }
                    }

                }
                //如果已存在相同的唯一字段，侧更新数据
                if (!onlyId.isEmpty()) {
                    //检测组合数据是否存在
                    assert query != null;
                    query.clear();
                    query.eq("pid", data.getPid())
                            .eq("tid", data.getTid())
                            .eq("is_del", "0");
                    if (!"".equals(parentId)) {
                        query.eq("parent_id", parentId);
                    }
                    Map<String, String> makeValue = new HashMap<>();
                    for (String field : makeOnlyFields.keySet()
                    ) {
                        cell = nRow.getCell(cols.get(field));
                        String cellValue = PublicUtil.getCellValue(cell).trim();
                        query.eq(camelToSnake(makeOnlyFields.get(field)), cellValue);
                        makeValue.put(field, cellValue);
                    }
                    query.last("limit 0, 1");
                    if (!makeValue.isEmpty()) {
                        switch (data.getModel()) {
                            case 1:
                                ArchivesRecord orData = recordService.getOne((Wrapper<ArchivesRecord>) query);
                                if (orData != null) {
                                    onlyId = orData.getId();
                                }
                                break;
                            case 2:
                                ArchivesFiles ofData = filesService.getOne((Wrapper<ArchivesFiles>) query);
                                if (ofData != null) {
                                    onlyId = ofData.getId();
                                }
                                break;
                            case 3:
                                /*
                                ArchivesProject opData = projectService.getOne((Wrapper<ArchivesProject>) query);
                                if (opData != null) {
                                    onlyId = opData.getId();
                                }

                                 */
                                break;
                        }
                    }
                }

                //开始写数据
                boolean write = false;
                log.info("开始导入数据");
                write = switch (data.getModel()) {
                    case 1 -> setArchivesRecord(loginUser, nRow, cols, fieldsList, i, data, parentId, onlyId);
                    case 2 -> setArchivesFiles(loginUser, nRow, cols, fieldsList, i, data, parentId, onlyId);
                    //case 3 -> setArchivesProject(loginUser, nRow, cols, fieldsList, i, data, onlyId);
                    default -> false;
                };

                if (write) {
                    if (!"".equals(onlyId)) {
                        updateNum++;
                    } else {
                        accNum++;
                    }
                } else {
                    errNum++;
                }
                InNum++;
                Thread.sleep(50);
            }

            workbook.close();
            long endTime = System.currentTimeMillis();
            long totalTime = endTime - startTime;  //用时
            data.setInfo("共导入 " + InNum + "条数据：其中新增" + accNum + "条;更新" + updateNum +
                    "条;失败 " + errNum + " 条。 用时：" + PublicUtil.getMillisToTime(totalTime));
            data.setStatus(2);
            updateById(data);
            return CompletableFuture.completedFuture(0);

        } catch (Exception e) {
            log.error(e.getLocalizedMessage());
            workbook.close();
            data.setStatus(3);
            data.setInfo(e.toString());
            updateById(data);
            return null;
        }

    }

    @Override
    public String imagesImport(Model model) {
        List<Projects> projectsList = projectsService.list(new QueryWrapper<Projects>().eq("is_del", "0"));
        model.addAttribute("projectsList", projectsList);
        return "/import/imagesImport";
    }

    @Override
    public AjaxResult getImagesImportData(Map<String, Object> params) {
        int limit = PublicConst.DEF_LIMIT;
        int page = PublicConst.DEF_PAGE;
        QueryWrapper<ArchivesImport> qw = new QueryWrapper<ArchivesImport>()
                .eq("import_model", "2")
                .orderByAsc("status")
                .orderByDesc("upload_time");
        for (String key : params.keySet()) {
            switch (key) {
                case "limit":
                    limit = Integer.parseInt(params.get(key).toString());
                    break;
                case "page":
                    page = Integer.parseInt(params.get(key).toString());
                    break;
                default:
                    qw.eq(key, params.get(key));
                    break;
            }
        }
        Page<ArchivesImport> data = page(new Page<>(page, limit), qw);
        return AjaxResult.success(data.getRecords(), data.getTotal());
    }

    @Override
    public String setImagesImportData(Model model, String pid, String tid, String id, String classifyId, String classifyModel) {
        ArchivesImport data = getById(id);
        List<ArchivesReceive> archivesReceiveList = null;
        if (data == null) {
            data = new ArchivesImport();
            data.setPid(pid);
            data.setTid(tid);
            data.setBatchCode(LocalDateTime.now().format(PublicConst.dateTimeFormatStr) + "图像导入");
            data.setClassifyModel(classifyModel);
            data.setClassifyId(classifyId);
        }
        archivesReceiveList = archivesReceiveService.list(new QueryWrapper<ArchivesReceive>()
                .select("batch_code")
                .eq("pid", pid)
                .eq("tid", tid)
                .eq("is_del", "0"));
        model.addAttribute("data", data);
        model.addAttribute("archivesReceiveList", archivesReceiveList);
        model.addAttribute("pid", pid);
        return "/import/setImagesImport";
    }

    @Override
    public AjaxResult saveImagesImportTask(HttpSession session, ArchivesImport data) {
        LoginUserInfo loginUser = redis.get(session.getId());
        if (loginUser == null) {
            return AjaxResult.error("没有找到登录用户信息，请重新登录");
        }
        if (data == null) {
            return AjaxResult.error("没有可保存的数据");
        }
        File dir = new File(mountPath + "/" + loginUser.getUserCode() + "/" + data.getFilename());
        if (!dir.exists() || !dir.isDirectory()) {
            return AjaxResult.error("挂接目录 " + data.getFilename() + " 不存在或不是一个有效的目录");
        }
        if (data.getId() == null || data.getId().isEmpty()) {
            data.setId(snowFlakeID.getId());
            data.setStatus(0);
            data.setImportModel("2");
            data.setUploader(loginUser.getUserName());
            data.setUploadTime(LocalDateTime.now());
            data.setCreator(loginUser.getUserCode());
        }
        return (saveOrUpdate(data)) ? AjaxResult.success("保存数据成功") : AjaxResult.error("保存数据失败");
    }

    @Override
    public AjaxResult ImagesImportExecute(HttpSession session, Map<String, Object> params) {
        LoginUserInfo loginUser = redis.get(session.getId());
        if (loginUser == null) {
            return AjaxResult.error("没有找到登录用户信息，请重新登录");
        }
        String id = params.getOrDefault("id", "").toString();
        String fillingModel = params.getOrDefault("fillingModel", "").toString();
        ArchivesImport data = getById(id);
        if (data == null) {
            return AjaxResult.error("没有找到需要执行的任务");
        }
        if ("".equals(fillingModel)) {
            return AjaxResult.error("没有找到需要执行的任务归档类别");
        }
        data.setExecutionTime(LocalDateTime.now());
        data.setExecutor(loginUser.getUserName());
        File srcDir = new File(mountPath + "/" + data.getCreator() + "/" + data.getFilename());
        if (!srcDir.exists() || !srcDir.isDirectory()) {
            data.setStatus(3);
            data.setInfo("挂接目录 " + data.getFilename() + " 不存在或不是一个有效的目录");
            updateById(data);
            return AjaxResult.error("挂接目录 " + data.getFilename() + " 不存在或不是一个有效的目录");
        }
        String onlyField = fieldConfigService.getOnlyField(data.getClassifyId(), fillingModel);
        if ("".equals(onlyField)) {
            data.setStatus(3);
            data.setInfo("该档案门类没有设置文件级元数据的唯一识别");
            updateById(data);
            return AjaxResult.error("该任务所属的档案门类没有设置文件级元数据的唯一识别");
        }

        data.setStatus(1);
        updateById(data);
        digitalFileService.imagesImportTaskExecute(loginUser, data, srcDir, onlyField, fillingModel);
        return AjaxResult.success("图像导入执行任务启动成功");
    }

    private boolean setArchivesFiles(LoginUserInfo loginUser, Row nRow, Map<String, Integer> cols, Map<String, String> fieldsList,
                                     int idx, ArchivesImport dataInputInfo, String parentId,
                                     String dataId) throws NoSuchFieldException, IllegalAccessException {
        //开始写数据
        ArchivesFiles archives = filesService.getById(dataId);
        if (archives == null) {
            archives = new ArchivesFiles();
            //ID
            archives.setId(snowFlakeID.getId());
            archives.setCreateTime(LocalDateTime.now());
            archives.setCreator(loginUser.getUserName());
            archives.setCreateModel("1");
            archives.setParentId(parentId);
            archives.setPid(dataInputInfo.getPid());
            archives.setTid(dataInputInfo.getTid());
            archives.setBatchCode(dataInputInfo.getBatchCode());
            archives.setStatus("0");
            archives.setIsDel("0");
            archives.setIsDigi("0");
            archives.setQc("0");
            //archives.setEntitystatus("0");
            archives.setInputid(dataInputInfo.getId());
            if ("".equals(dataInputInfo.getBatchCode())) {

            }
        } else {
            archives.setUpdateTime(String.valueOf(LocalDateTime.now()));
            archives.setUpdater(loginUser.getUserName());
        }

        Field field;
        //开始循环值
        String OneKey = "";
        Cell cell;
        for (String key : cols.keySet()) {
            //如果字段配置中没有该字段，侧抛弃s
            if (!fieldsList.containsKey(key)) {
                continue;
            }
            cell = nRow.getCell(cols.get(key));
            String cellValue = PublicUtil.getCellValue(cell).trim();
            field = archives.getClass().getDeclaredField(fieldsList.get(key));
            field.setAccessible(true);
            field.set(archives, cellValue);
        }
        try {
            boolean save;
            if ("".equals(dataId)) {
                ArchivesInfo archivesInfo = new ArchivesInfo();
                archivesInfo.setId(snowFlakeID.getId());
                archivesInfo.setPid(archives.getPid());
                archivesInfo.setTid(archives.getTid());
                archivesInfo.setArchivesId(archives.getId());
                archivesInfoService.save(archivesInfo);
                save = filesService.save(archives);
                archivesLogsService.newLog(loginUser, archives.getId(), archives.getArchivalCode(), "批量导入数据", archives.getPid(), archives.getTid());
            } else {
                save = filesService.updateById(archives);
                archivesLogsService.newLog(loginUser, archives.getId(), archives.getArchivalCode(), "批量更新数据", archives.getPid(), archives.getTid());
            }
            if (!save) {
                LogData(dataInputInfo.getId(), idx, OneKey + "数据导入失败，错误信息：");
                return false;
            } else {
                return true;
            }

        } catch (Exception e) {
            String errInfo = e.getMessage();
            int iv = errInfo.indexOf("###", 4);
            if (iv < 0) {
                iv = errInfo.length();
            }
            LogData(dataInputInfo.getId(), idx, OneKey + "数据导入失败，错误信息：" + errInfo.substring(0, iv));
            return false;
        }
    }

    /**
     * 项目数据导入
     *
     */
    /*
    private boolean setArchivesProject(LoginUser loginUser, Row nRow, Map<String, Integer> cols, Map<String, String> fieldsList,
                                       int idx, ArchivesImport dataInputInfo,
                                       String dataId) throws NoSuchFieldException, IllegalAccessException {
        //开始写数据
        //开始写数据
        ArchivesProject archives = projectService.getById(dataId);
        if (archives == null) {
            archives = new ArchivesProject();
            //ID
            archives.setId(snowFlakeID.getId());
            archives.setCreateTime(LocalDateTime.now());
            archives.setCreater(loginUser.getUserName());
            archives.setCreateModel("1");
            archives.setPid(dataInputInfo.getPid());
            archives.setTid(dataInputInfo.getTid());
            archives.setBatchcode(dataInputInfo.getBatchcode());
            archives.setStatus("0");
            archives.setIsdel("0");
            archives.setDigi("0");
            archives.setIsqc("0");
            archives.setEntitystatus("0");
            //archives.setInputid(dataInputBody.getPid());
        } else {

        }

        Field field;
        //开始循环值
        String OneKey = "";
        Cell cell;
        for (String key : cols.keySet()) {
            //如果字段配置中没有该字段，侧抛弃s
            if (!fieldsList.containsKey(key)) {
                continue;
            }
            cell = nRow.getCell(cols.get(key));
            String cellValue = PublicUtil.getCellValue(cell).trim();
            field = archives.getClass().getDeclaredField(fieldsList.get(key));
            field.setAccessible(true);
            field.set(archives, cellValue);
        }
        try {
            boolean save;
            if ("".equals(dataId)) {
                save = projectService.save(archives);
                archivesLogsService.newLog(loginUser, archives.getId(), archives.getProjectcode(), "批量导入数据", archives.getPid(), archives.getTid());
            } else {
                save = projectService.updateById(archives);
                archivesLogsService.newLog(loginUser, archives.getId(), archives.getProjectcode(), "批量更新数据", archives.getPid(), archives.getTid());
            }
            if (!save) {
                LogData(dataInputInfo.getId(), idx, OneKey + "数据导入失败，错误信息：");
                return false;
            } else {
                return true;
            }

        } catch (Exception e) {
            String errInfo = e.getMessage();
            int iv = errInfo.indexOf("###", 4);
            LogData(dataInputInfo.getId(), idx, OneKey + "数据导入失败，错误信息：" + errInfo.substring(0, iv));
            return false;
        }
    }

     */
    private boolean setArchivesRecord(LoginUserInfo loginUser, Row nRow, Map<String, Integer> cols, Map<String, String> fieldsList,
                                      int idx, ArchivesImport dataInputInfo, String parentId,
                                      String dataId) throws NoSuchFieldException, IllegalAccessException {

        //开始写数据
        ArchivesRecord archives = recordService.getById(dataId);
        if (archives == null) {
            archives = new ArchivesRecord();
            archives.setId(snowFlakeID.getId());
            archives.setCreateTime(LocalDateTime.now());
            archives.setCreator(loginUser.getUserName());
            archives.setCreateModel("1");
            archives.setParentId(parentId);
            archives.setPid(dataInputInfo.getPid());
            archives.setTid(dataInputInfo.getTid());
            archives.setBatchCode(dataInputInfo.getBatchCode());
            archives.setStatus("0");
            archives.setIsDel("0");
            archives.setIsDigi("0");
            archives.setQc("0");
            archives.setInputId(dataInputInfo.getId());
        } else {
            archives.setUpdateTime(String.valueOf(LocalDateTime.now()));
            archives.setUpdater(loginUser.getUserName());
        }
        Field field;
        //开始循环值
        String OneKey = "";
        Cell cell;
        for (String key : cols.keySet()) {
            //如果字段配置中没有该字段，侧抛弃s
            if (!fieldsList.containsKey(key)) {
                continue;
            }
            cell = nRow.getCell(cols.get(key));
            String cellValue = PublicUtil.getCellValue(cell).trim();
            field = archives.getClass().getDeclaredField(fieldsList.get(key));
            field.setAccessible(true);
            field.set(archives, cellValue);
        }
        try {
            boolean save = false;
            /*


            if ("".equals(dataId)) {
                        ArchivesInfo archivesInfo = new ArchivesInfo();
            archivesInfo.setId(snowFlakeID.getId());
            archivesInfo.setPid(archives.getPid());
            archivesInfo.setTid(archives.getTid());
            archivesInfo.setArchivesid(archives.getId());
            archivesInfoService.save(archivesInfo);
                save = recordService.save(archives);
                archivesLogsService.newLog(loginUser, archives.getId(), archives.getArchivalCode(), "批量导入数据", archives.getPid(), archives.getTid());
            } else {
                save = recordService.updateById(archives);
                archivesLogsService.newLog(loginUser, archives.getId(), archives.getArchivalCode(), "批量更新数据", archives.getPid(), archives.getTid());
            }*/
            if (!save) {
                LogData(dataInputInfo.getId(), idx, OneKey + "数据导入失败，错误信息：");
                return false;
            }

            return true;
        } catch (Exception e) {
            String errInfo = e.getMessage();
            int iv = errInfo.indexOf("###", 4);
            LogData(dataInputInfo.getId(), idx, OneKey + "数据导入失败，错误信息：" + errInfo.substring(0, iv));
            return false;
        }
    }

    private void LogData(String pid, int idx, String info) {
        ArchivesImportLog data = new ArchivesImportLog();
        data.setId(snowFlakeID.getId());
        data.setPid(pid);
        data.setIdx(idx);
        data.setInfo(info);
        data.setResult("失败");
        archivesImportLogService.save(data);
    }
}
